<template>
  <div class="hello">
    <!-- 搜索框 -->
    <div class="search-container">
      <el-input
          v-model="searchQuery"
          placeholder="输入搜索内容"
          clearable
          @clear="clearSearch"
          @keyup.enter.native="performSearch"
      >
        <template #append>
          <el-button icon="el-icon-search" @click="performSearch"></el-button>
        </template>
      </el-input>

    </div>

    <el-table
        :data="tableData"
        style="width: 100%"
        height="250"
        @row-click="handleRowClick"
    >
      <el-table-column
          align="center"
          label="序号"
          type="index"
      >
      </el-table-column>
      <el-table-column
          prop="name"
          align="center"
          label="文件名字"
          width="150"
      >
        <template #default="scope">
          <span class="filename" @click="previewPdf" :style="" style="color:#5a94cc">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column
          align="center"
          prop="content"
          label="文件内容"
      >
        <template #default="{ row }">
          <span v-html="highlightContent(row.content)"></span>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
        :visible.sync="dialogVisible"
        width="100%"
        :fullscreen="true"
        :before-close="handleClose">
      <div style="display: flex;">
<!--        <el-scrollbar style="height: 100%">-->
          <div style="flex-shrink: 0;width: 200px;background-color: #e1e4e5;font-size: 12px" v-if="searchResult && searchResult.length>0">
            <el-scrollbar style="height: 100%">
              <div @click="jumpPreview(item,index)" class="preview-list" :class="{'preview-active':previewIndex===index}"
                   v-for="(item,index) in searchResult"
                   style="margin: 10px 10px;display: flex;justify-content: space-between;cursor: pointer">
                <span style="max-width: 80%;overflow: hidden;text-overflow: ellipsis;white-space: nowrap">{{ item.preview }}</span> <span>{{ item.page + 1 }}</span>
              </div>
            </el-scrollbar>

          </div>
<!--        </el-scrollbar>-->

        <div id="pdfView" ref="pdfView" class="gl-pdf-viewer__canvas">
          <form @submit.prevent>
            <iframe id="previewPdf"
                    v-if="pdfUrl!==''"
                    :style="pdfStyle"
                    :src="'./pdf/web/viewer.html?file=' + encodeURIComponent(pdfUrl + '#' + title)+ '&downloadDisable=' + downloadDisable+'&query=' + encodeURIComponent(searchQuery)"
            />
          </form>
        </div>
      </div>

    </el-dialog>

  </div>
</template>

<script>
import pdf from "vue-pdf"

export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data() {
    return {
      dialogVisible: false,
      allData: [],
      tableData: [
        {
          name: '总经理声明',
          content: 'All departments and ships of the Company involved in occupational health, safety,\n' +
              'quality and environment management activities must strictly follow the provisions specified\n' +
              'in the HSQE management system documents, ensuring that all works are in compliance with\n' +
              'the requirements on health, safety, quality and environmental protection, and the HSQE\n' +
              'management system （HSQEMS）of the Company is working continuously and effectively.\n' +
              '公司涉及健康、安全、质量和环境管理活动的所有部门和船舶都必须严格执行体系文件的各项\n' +
              '规定，以确保各项工作符合健康、安全、质量和环境规范的要求，确保公司健康、安全、质量和环\n' +
              '境管理体系（下称：“HSQE 管理体系”；英文缩写：“HSQEMS”）有效、持续地运行。\n' +
              'In order to ensure an effective operation of the HSQEMS, I hereby designate Mr. Wang\n' +
              'Xiaodong as Designated Person of the Company and Mr. Zhang Jian as the First Substitute, I\n' +
              'authorize him/them to be responsible for supervising the HSQEMS operation routinely and\n' +
              'organizing the implementation of relevant provisions of the HSQEMS documents.\n' +
              '为保证HSQE 管理体系有效运行，我任命王晓冬为公司的指定人员，张健为第一替代人员，并\n' +
              '授权其负责HSQE 管理体系运行的日常监督工作，组织实施体系文件相关规定。\n' +
              'The Designated Person, under the leadership of the Managing Director, shall ensure the\n' +
              'effective operation of the Company’s HSQEMS through coordination and supervision; ensure\n' +
              'that the policy and objectives of HSQEMS are established, and are compatible with the\n' +
              'context and strategic direction of the Company; ensure that the HSQEMS achieves its\n' +
              'intended results; organize to compile the HSQEMS documents in combination with the\n' +
              'effective business operation of the Company, promote the use of the process approach and\n' +
              'risk-based thinking to ensure that the resources needed for the HSQEMS are available.\n' +
              '指定人员在总经理的领导下，通过协调和监督，确保公司HSQE 管理体系有效运行；确保制定\n' +
              'HSQE 管理方针及目标，并与公司的环境和战略方向相一致；确保HSQE 管理体系达成预期结果；\n' +
              '组织编写HSQE 管理体系，结合公司的业务有效运作，促进使用过程方法及基于风险的思维，确保\n' +
              'HSQE 管理体系获得必要的资源支持。\n' +
              'The Company shall transmit the significance of meeting the requirement of customer,\n' +
              'statutory and regulatory to staff through meeting, training or media, ensure that：\n' +
              '公司通过各种会议、培训、媒体的舆论导向等途径向员工传达满足客户和法律、法规要求的重\n' +
              '要性:\n' +
              '1. The Company’s businesses are in compliance with international sanctions rules, respect\n' +
              'the market principles, abide by applicable laws and regulations, and contribute to the\n' +
              'establishment of a fair and positive market environment.\n' +
              '确保公司经营业务遵循国际制裁法规，遵守市场规则，合法合规，共同营造公平公正的商业环\n',
          title: "1.3.1-Managing Director's Statement-总经理声明.pdf",
          pdfUrl: "/pdf/1.1-Contents of the HSQEManagement System-HSQE 管理体系总目录.pdf"
        },
        {
          name: 'HSQE管理体系总目录',
          content: 'General\n' +
              '总则\n' +
              '1.1 Contents of the HSQE Management System\n' +
              'HSQE 管理体系总目录\n' +
              '1.2 Terms and Definitions\n' +
              '术语与定义\n' +
              '1.3 Statement andAppointment\n' +
              '声明与任命\n' +
              '1.3.1 Managing Director’s Statement\n' +
              '总经理声明\n' +
              '1.3.2 Workers’representatives\n' +
              '员工代表\n' +
              '1.4 Company Profile\n' +
              '公司简介\n' +
              '1.4.1 Company Overview\n' +
              '公司概况\n' +
              '1.4.2 Organization and Job Description\n' +
              '组织架构和职责范围（公司）\n' +
              '1.5 Management System\n' +
              '管理体系\n' +
              '1.5.1 HSQE Management System\n' +
              'HSQE 管理体系\n' +
              '1.5.2 Ship Security Plan\n' +
              '船舶保安计划\n' +
              '1.5.3 Maritime Labor Convention\n' +
              '海事劳工\n' +
              '1.6 Policies and Objectives\n' +
              '方针及目标\n' +
              '1.6.1 Health, Safety, Quality and Environment Protection Policy\n' +
              '健康、安全、质量和环境保护方针\n' +
              '1.6.2 Health, Safety, Quality and Environment Management Objectives\n' +
              '健康、安全、质量和环境管理目标\n' +
              '1.6.3 Drug andAlcohol Control Policy\n',
          title: "1.1-Contents of the HSQEManagement System-HSQE 管理体系总目录.pdf",
          pdfUrl: "/pdf/1.1-Contents of the HSQEManagement System-HSQE 管理体系总目录.pdf"
        },
        {
          name: 'HSQE管理体系总目录',
          content: 'test',
          title: "test.pdf",
          pdfUrl: "/pdf/test.pdf"
        },
      ],
      searchQuery: '',
      currentPdfRow: null,
      showPdfViewer: false,
      pdfUrl: "",
      title: "",
      downloadDisable: "",
      transform: {
        scale: 100,
        pageRotate: 0,
        offsetX: 0,
        offsetY: 0,
        enableTransition: false
      },
      previewIndex: null,
      searchResult: []
    }
  },
  mounted() {
    this.allData = this.tableData;
    document.cookie = "Admin-Token=789164"
  },
  methods: {
    jumpPreview(item, index) {
      this.previewIndex = index;

      console.log(item)
      this?.ifWindow.jumpSearchResult(item.page, item.matchCount)
      console.log();

    },
    handleIframeMessage(event) {
      if (event.data.type === 'searchResult') {
        this.searchResult = event.data.payload;
      }
    },
    previewPdf(fileData) {
      this.pdfUrl = fileData.pdfUrl;
      this.title = fileData.title;
      this.dialogVisible = true;
      this.searchResult = []

      this.$nextTick(()=>{
        this.ifWindow = document.getElementById("previewPdf").contentWindow;
      });

      // 监听 iframe 发来的消息
      window.addEventListener('message', this.handleIframeMessage);
    },
    handleClose() {
      this.dialogVisible = false;
    },
    performSearch() {
      if (!this.searchQuery.trim()) {
        this.clearSearch();
        return;
      }

      const query = this.searchQuery;


      this.tableData = this.allData.filter(item => {
        console.log(item.content.includes(query))
        return item.content.includes(query)
      })

    },

    clearSearch() {
      this.searchQuery = '';
      this.currentPdfRow = null;
      this.tableData = this.allData;
    },

    highlightContent(content) {
      if (!this.searchQuery || !content) return content;

      const regex = new RegExp(this.searchQuery, 'gi');
      return content.replace(regex, match =>
          `<span style="background-color: yellow; font-weight: bold;">${match}</span>`
      );
    },

    handleRowClick(row) {
      this.currentPdfRow = row;
      this.showPdfViewer = true;
      this.pdfUrl = row.pdfUrl;
      this.title = row.title;
    }
  },
  computed: {
    pdfStyle() {
      const {scale, enableTransition} = this.transform
      const style = {
        width: parseInt(scale) + '%',
        transition: enableTransition ? 'width .3s' : '',
        height: '86vh'
      }
      return style;
    }
  }
}
</script>

<style scoped>
.hello {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.search-container {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.gl-pdf-viewer__canvas {
  width: 100%;
  height: 100%;
  align-items: center;
  overflow-y: auto;
}

.el-table {
  margin-bottom: 20px;
}

.el-table /deep/ .el-table__body tr:hover > td {
  background-color: #f5f7fa;
  cursor: pointer;
}

.filename:hover {
  text-decoration: underline;
}

.preview-list:hover {
  background-color: #d5d7d6;
}

.preview-active {
  background-color: #cbcdcc;
}
</style>